<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute } from 'vue-router'
import { useArticleStore } from '@/stores/articleStore'
import { storeToRefs } from 'pinia'
import { Edit, Delete, Search } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import { useTokenStore } from '@/stores/token'
import {
  articleUpdateService,
  articleAddService,
  articleDeleteService,
  articleTagAddService,
  articleTagUpdateService,
  articleTagDeleteService,
  articleTagDeleteAllService
} from '@/apis/article.js'

const articleStore = useArticleStore()
const {
  tags,
  tagIds,
  categorys,
  pageNum,
  total,
  pageSize,
  categoryId,
  state,
  search,
} = storeToRefs(articleStore)
const route = useRoute()

onMounted(() => {
  articleStore.fetchCategories()
  articleStore.fetchArticles()
})
// 新增路由监听：解决侧边栏跳转不刷新问题
// 当路由路径变化时，重新获取分类和文章数据
// 避免组件复用导致的onMounted不触发问题
watch(() => route.path, () => {
  articleStore.fetchCategories()
  articleStore.fetchArticles()
})

// 监听搜索变化
let filterTimer = null
const handleSearchInput = () => {
  clearTimeout(filterTimer)
  filterTimer = setTimeout(() => {
    articleStore.fetchArticles()
  }, 200)
}

watch([categoryId, state, tagIds], () => {
  handleSearchInput()
})

watch(search, (newVal) => {
  if (newVal === '') {
    articleStore.fetchArticles()
  } else {
    handleSearchInput()
  }
})

//控制抽屉是否显示
const dialogVisible = ref(false)
//添加表单数据模型
const articleModel = ref({
  title: '',
  categoryId: '',
  coverImg: '',
  content: '',
  tagIds: '',
  tagNames: '',
  state: ''
})
const tokenStore = useTokenStore();
//上传成功的回调函数
const uploadSuccess = (result) => {
  articleModel.value.coverImg = result.data;
  console.log(result.daata);
}
//添加文章
const addArticle = async () => {
  // 调用接口
  let result = await articleAddService(articleModel.value)

  ElMessage.success(result.msg ? result.msg : '添加成功')
  // 让抽屉消失
  dialogVisible.value = false;
  // 刷新
  articleStore.fetchArticles();
}
// 清空
const clearData = () => {
  title.value = '添加文章'
  articleModel.value.title = '';
  articleModel.value.categoryId = '';
  articleModel.value.coverImg = '';
  articleModel.value.content = ' ';
  articleModel.value.tagIds = '';
  articleModel.value.state = '';
}
// 定义变量，控制标题的展示
const title = ref('')
// 编辑文章
const updateArticle = () => {
  // 调用接口
  let result = articleUpdateService(articleModel.value);

  try {
    let updateTags = articleTagUpdateService(articleModel.value.id, articleModel.value.tagIds);
    console.log('更新标签成功:', updateTags);
  }
  catch (error) {
    console.error('添加标签失败:', error);
  }


  ElMessage.success(result.msg ? result.msg : '修改成功')
  // 调用获取所有文章的函数（刷新
  articleStore.fetchArticles();
  dialogVisible.value = false;
}
// 编辑弹窗数据
const editArticle = (row) => {
  dialogVisible.value = true;
  title.value = '编辑文章';
  articleModel.value.title = row.title;
  articleModel.value.categoryId = row.categoryId;
  articleModel.value.coverImg = row.coverImg
  articleModel.value.content = row.content
  //  row.tagIds 中的字符串ID转换为数字ID用于回显
  if (Array.isArray(row.tagIds)) {
    articleModel.value.tagIds = row.tagIds.map(id => Number(id));
  } else {
    articleModel.value.tagIds = []; // 如果 row.tagIds 不是数组或为null/undefined，则设为空数组
  }
  articleModel.value.tagNames = row.tagNames
  articleModel.value.state = row.state
  // 扩展id属性，将来需要传给后台，完成分类的修改
  articleModel.value.id = row.id;
  console.log(articleModel);

}
// 删除文章
const deleteArticle = (row) => {
  // 提示用户 确认框
  ElMessageBox.confirm(
    '确认删除该文章？',
    '温馨提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      // 调用接口 
      let result = await articleDeleteService(row.id);
      ElMessage({
        type: 'success',
        message: '删除成功',
      })
      // 刷新列表
      articleStore.fetchArticles();
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',

      })
    })
}

// 格式化分类显示
const formatCategory = (row) => {
  const category = categorys.value.find(c => c.id === row.categoryId)
  return category ? category.categoryName : '未知分类'
}

// 测试用，查看是否传递了tagIds
const handleTagChange = (selectedIds) => {
  console.log(articleModel.value);
}

</script>

<template>
  <el-card class="page-container">
    <template #header>
      <div class="head">
        <div class="card-header">
          文章管理
        </div> 
        <el-button type="primary" class="add-button" @click="dialogVisible = true; clearData();">+添加文章</el-button>
      </div>
    </template>

    <!-- 分类搜索 -->
    <el-form inline >
      <el-form-item label="文章分类：" style="font-size: 17px;">
        <el-select placeholder="请选择" v-model="categoryId" style="width: 120px">
          <el-option label="全部" value="" style="text-align: center;"></el-option>
          <el-option
              v-for="c in categorys"
              :key="c.id"
              :label="c.categoryName"
              :value="c.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="文章标签："  style="font-size: 17px;">
        <el-select placeholder="请选择" v-model="tagIds" style="width: 120px" >
          <el-option label="全部" value="" style="text-align: center;"></el-option>
          <el-option
              v-for="t in tags"
              :key="t.id"
              :label="t.tagName"
              :value="t.tagId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="发布状态：" >
        <el-select placeholder="请选择" v-model="state" style="width: 100px">
            <el-option label="全部" value="" style="text-align: center;"></el-option>
            <el-option label="已发布" value="已发布"></el-option>
            <el-option label="草稿" value="草稿"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="文章搜索：">
        <el-input v-model="search"
        placeholder="请输入文章标题"
        style="width: 200px"
        :prefix-icon="Search"
        @input="handleSearchInput"></el-input>
      </el-form-item>

      <el-form-item>
        <el-button @click="categoryId = ''; state = ''; search = ''; $nextTick(() => articleStore.fetchArticles())">重置</el-button>
      </el-form-item>
      
    </el-form>
   
    <div class="article-management">
      <el-table
        :data="articleStore.articles"
        :row-style="{ height: '50px' }"
        :cell-style="{ paddingTop: '2.5px' }"
        style="width: 100%; font-size: 15px"
      >
        <el-table-column label="文章标题" width="300" prop="title">
          <template #default="{ row }">
            <el-link type="primary" @click="$router.push(`/articleView/${row.id}`)">{{ row.title }}</el-link>
          </template>
        </el-table-column>
        <el-table-column label="分类"  prop="categoryId" :formatter="formatCategory"></el-table-column>
        <el-table-column label="标签" width="200" prop="tagIds" :formatter="formatCategory">
          <template #default="scope">
          <!-- 遍历标签数组 -->
            <div style="display: flex; gap: 5px; flex-wrap: wrap">
              <el-tag 
                v-for="(tag, index) in scope.row.tagNames" 
                :key="index"
                type="primary"
                size="small"
              >
                {{ tag }}
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="发表时间" prop="createTime"></el-table-column>
        <el-table-column label="状态" prop="state"></el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button :icon="Edit" circle plain type="primary" @click="editArticle(row)"></el-button>
            <el-button :icon="Delete" circle plain type="danger" @click="deleteArticle(row)"></el-button>
          </template>
        </el-table-column>
        <template #empty>
          <el-empty description="没有数据" />
        </template>
      </el-table>
    </div>

    <!-- 分页条 -->
    <el-pagination background 
          v-model:current-page="pageNum" 
          v-model:page-size="pageSize" 
          :page-sizes="[3, 5, 10, 15]"
          layout="jumper, total, sizes, prev, pager, next"
          :total="total" 
          @size-change="articleStore.onSizeChange"
          @current-change="articleStore.onCurrentChange" 
          style="margin-top: 20px; justify-content: flex-end" />


     <!-- 抽屉 -->
    <el-dialog v-model="dialogVisible" :title="title" direction="rtl" >
        <!-- 添加文章表单 -->
      <el-form :model="articleModel" label-width="100px" >
          <el-form-item label="文章标题" >
              <el-input v-model="articleModel.title" placeholder="请输入标题"></el-input>
          </el-form-item>
          <el-form-item label="文章分类">
              <el-select placeholder="请选择" v-model="articleModel.categoryId">
                  <el-option 
                  v-for="c in categorys" 
                  :key="c.id" 
                  :label="c.categoryName" 
                  :value="c.id">
                  </el-option>
              </el-select>
          </el-form-item>
          <el-form-item label="文章标签">
              <el-select
                v-model="articleModel.tagIds"            
                multiple
                filterable
                placeholder="请选择标签"
                style="width: 100%"
                :filter-method="filterTag"
                @change="handleTagChange"
              >
              <el-option
                v-for="t in tags"
                :key="t.id"
                :label="t.tagName"
                :value="t.tagId">  
              </el-option>
              </el-select>
          </el-form-item>
          <el-form-item label="文章状态">
            <el-select placeholder="请选择" v-model="articleModel.state" >
              <el-option 
                label="已发布" 
                value="已发布">
              </el-option>
              <el-option 
                label="草稿" 
                value="草稿">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="文章封面" class="img">
              <!--
                  auto-upload:设置是否自动上传
                  action：设置服务器接口路径
                  name：设置上传的文件字段名
                  headers：设置上传的请求头
                  on-success:设置上传成功的回调函数
                -->
              <el-upload class="avatar-uploader" :auto-upload="true" :show-file-list="false"
                  action="/api/upload"
                  name="file"
                  :headers="{ 'Authorization': tokenStore.token }"
                  :on-success="uploadSuccess"
                  >
                  <img v-if="articleModel.coverImg" :src="articleModel.coverImg" class="avatar" />
                  <el-icon v-else class="avatar-uploader-icon">
                      <Plus />
                  </el-icon>
              </el-upload>
          </el-form-item>
          <el-form-item label="文章内容" style="height: 300px;">
              <!-- 修改这里：移除高度样式，添加editor-container -->
            <div class="editor-container">
              <div class="editor">
                <quill-editor
                  theme="snow"
                  v-model:content="articleModel.content"
                  contentType="html"
                ></quill-editor>
              </div>
            </div>
          </el-form-item>
          <el-form-item class="form-buttons">
              <el-button type="primary" @click="title == '添加文章' ? addArticle() : updateArticle()">发布</el-button>
              <el-button type="info" @click="dialogVisible = false">取消</el-button>
          </el-form-item> 
      </el-form>
      
    </el-dialog>         
  </el-card>
</template>



<style>
.page-container {
  min-height: 86.5vh;
  box-sizing: border-box;

  .head {
    display: flex;

    .card-header {
      text-align: center;
      font-size: 25px;
    }

    .add-button {
      margin-left: auto;
      margin-top: 5px;
    }

  }
}

.el-card {
  background-color: #ffffff;
  margin: 10px;
  height: auto;

  /* 让RouterView占用剩余空间 */
  .search {
    padding-left: 12px;
    padding-bottom: 10px;

    & input {
      width: 40vh;
      height: 4vh;
    }
  }

  .el-form {
    padding-top: 10px;
  }

  .el-table-column {
    height: 100px;
  }

}

.img {
  height: auto;
  width: auto;
}

.tag {
  margin: 10px;

  .tag-header {
    font-family: var(--el-font-family);
    /* 使用Element Plus字体 */
    font-size: 14px;
    /* 标准字体大小 */
    color: var(--el-text-color-regular);
    /* 使用主题文本颜色 */
    margin-bottom: 10px;
    display: flex;
    align-items: center;
  }

  .tag-list {
    margin-top: 10px;

    .tag-item {
      margin-right: 5px;
    }
  }
}

.avatar-uploader {
  :deep() {
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }

    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }

    .el-upload:hover {
      border-color: var(--el-color-primary);
    }

    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      text-align: center;
    }
  }
}

.el-dialog {
  padding: 30px;
  padding-right: 50px;
  display: flex;
  flex-direction: column;
  margin: 0 !important;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  max-height: calc(100% - 30px);
  max-width: calc(100% - 30px);
}

/* 编辑器容器样式 */
.editor-container {
  width: 100%;
  height: 300px;
  /* 固定高度 */
  position: relative;
  margin-bottom: 20px;
  /* 增加底部间距 */
}

.editor {
  width: 100%;
  height: 100%;
  margin-top: 10px;
  margin-bottom: 10px;
  border-radius: 5px;
  background-color: #fcfcfc;
  overflow: hidden;
  /* 防止内容溢出 */
}

/* 确保Quill编辑器不会扩展到按钮区域 */
:deep(.ql-container) {
  height: calc(100% - 42px) !important;
  /* 减去工具栏高度 */
}

/* 按钮区域样式 */
.form-buttons {
  margin-top: 20px;
  /* 增加与编辑器的间距 */
}
</style>


